<template>
  <xui-bottom-popup ref="popupRef">
    <view class="xui-datepicker">
      <view class="xui-datepicker__header">
        <view class="xui-datepicker__header__cancel" @click="cancel">取消</view>
        <view class="xui-datepicker__header__confirm" @click="confirm">确定</view>
      </view>

      <view class="xui-datepicker__body">
        <picker-view :value="value" @change="pickerChange" class="xui-datepicker-view" :indicator-class="indicatorClass">
          <picker-view-column v-if="!reset && (type < 4 || type == 7 || type == 8)">
            <view class="xui-datepicker-column-item" v-for="(item, index) in years" :key="index">{{ item }}年</view>
          </picker-view-column>
          <picker-view-column v-if="!reset && (type < 4 || type == 7 || type == 8)">
            <view class="xui-datepicker-column-item" v-for="(item, index) in months" :key="index">{{ formatNum(item) }}月
            </view>
          </picker-view-column>
          <picker-view-column v-if="!reset && (type == 1 || type == 2 || type == 7 || type == 8)">
            <view class="xui-datepicker-column-item" v-for="(item, index) in days" :key="index">{{ formatNum(item) }}日
            </view>
          </picker-view-column>
          <picker-view-column v-if="!reset && (type == 1 || type == 4 || type == 5 || type == 7 || type == 8)">
            <view class="xui-datepicker-column-item" v-for="(item, index) in hours" :key="index">{{ formatNum(item) }}时
            </view>
          </picker-view-column>
          <picker-view-column v-if="!reset && (type == 1 || type > 3) && type != 8">
            <view class="xui-datepicker-column-item" v-for="(item, index) in minutes" :key="index">{{ formatNum(item) }}分
            </view>
          </picker-view-column>
          <picker-view-column v-if="!reset && type > 4 && type != 8">
            <view class="xui-datepicker-column-item" v-for="(item, index) in seconds" :key="index">{{ formatNum(item) }}秒
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
  </xui-bottom-popup>
</template>

<script>
import { computed, onMounted, watch, reactive, ref } from 'vue'

export default {
  name: 'XuiDatePicker',
  props: {
    // 1-日期+时间（年月日+时分） 2-日期(年月日) 3-日期(年月) 4-时间（时分） 5-时分秒 6-分秒 7-年月日 时分秒 8-年月日+小时
    type: {
      type: Number,
      default: 2
    },
    // 年份区间
    startYear: {
      type: Number,
      default: 1960
    },
    // 年份区间
    endYear: {
      type: Number,
      default: 2050
    },
    // 设置默认显示日期 2019-08-01 || 2019-08-01 17:01 || 2019/08/01
    setDateTime: {
      type: String,
      default: ''
    },
    indicatorClass: {
      type: String,
      default: 'indicator-class'
    }
  },
  emits: ['cancel', 'confirm'],
  setup (props, { emit }) {
    const popupRef = ref()
    const open = () => {
      // console.log(this.year)
      // console.log(this.months)
      // 根据版本日期 显示具体的月份
      // if (this.year === 2022) {
      //   this.months = [1, 2]
      // }
      setTimeout(() => {
        popupRef.value.open()
      }, 50)
    }
    const close = () => {
      popupRef.value.close()
    }
    const cancel = () => {
      popupRef.value.close()
      emit('cancel', {})
    }

    const years = reactive([])
    const months = reactive([])
    const days = reactive([])
    const hours = reactive([])
    const minutes = reactive([])
    const seconds = reactive([])
    const year = ref(0)
    const month = ref(0)
    const day = ref(0)
    const hour = ref(0)
    const minute = ref(0)
    const second = ref(0)
    const value = ref([0, 0, 0, 0, 0, 0])
    const reset = ref(false)

    onMounted(() => {
      setTimeout(() => {
        initData()
      }, 20)
    })

    const yearOrMonth = computed(() => {
      return `${year.value}-${month.value}`
    })
    const propsChange = computed(() => {
      return `${props.setDateTime}-${props.type}-${props.startYear}-${props.endYear}`
    })

    watch(
      () => yearOrMonth.value,
      () => {
        setDays()
      }
    )
    watch(
      () => propsChange.value,
      () => {
        reset.value = true
        setTimeout(() => {
          initData()
        }, 20)
      }
    )
    watch(
      () => year.value,
      (n) => {
        console.log(n)
      }
    )

    const formatNum = (num) => {
      return num < 10 ? '0' + num : num + ''
    }
    const generateArray = (start, end) => {
      return Array.from(new Array(end + 1).keys()).slice(start)
    }
    const getIndex = (arr, val) => {
      const index = arr.indexOf(val)
      return ~index ? index : 0
    }
    // 日期时间处理
    const initSelectValue = () => {
      let fdate = props.setDateTime.replace(/-/g, '/')
      fdate = fdate && fdate.indexOf('/') === -1 ? `2022/01/01 ${fdate}` : fdate
      let time = null
      if (fdate) time = new Date(fdate)
      else time = new Date()
      year.value = time.getFullYear()
      month.value = time.getMonth() + 1
      day.value = time.getDate()
      hour.value = time.getHours()
      minute.value = time.getMinutes()
      second.value = time.getSeconds()
    }
    const initData = () => {
      initSelectValue()
      reset.value = false
      switch (props.type) {
        case 1:
          value.value = [0, 0, 0, 0, 0]
          setYears()
          setMonths()
          setDays()
          setHours()
          setMinutes()
          break
        case 2:
          value.value = [0, 0, 0]
          setYears()
          setMonths()
          setDays()
          break
        case 3:
          value.value = [0, 0]
          setYears()
          setMonths()
          break
        case 4:
          value.value = [0, 0]
          setHours()
          setMinutes()
          break
        case 5:
          value.value = [0, 0, 0]
          setHours()
          setMinutes()
          setSeconds()
          break
        case 6:
          value.value = [0, 0]
          setMinutes()
          setSeconds()
          break
        case 7:
          value.value = [0, 0, 0, 0, 0, 0]
          setYears()
          setMonths()
          setDays()
          setHours()
          setMinutes()
          setSeconds()
          break
        case 8:
          value.value = [0, 0, 0, 0]
          setYears()
          setMonths()
          setDays()
          setHours()
          break
        default:
          break
      }
    }
    const setYears = () => {
      years.length = 0
      generateArray(props.startYear, props.endYear).forEach(el => years.push(el))
      setTimeout(() => {
        value.value[0] = getIndex(years, year.value)
      }, 8)
    }
    const setMonths = () => {
      months.length = 0
      generateArray(1, 12).forEach(el => months.push(el))
      setTimeout(() => {
        value.value[1] = getIndex(months, month.value)
      }, 8)
    }
    const setDays = () => {
      if (props.type === 3 || props.type === 4) return
      const totalDays = new Date(year.value, month.value, 0).getDate()
      days.length = 0
      generateArray(1, totalDays).forEach(el => days.push(el))
      setTimeout(() => {
        value.value[2] = getIndex(days, day.value)
      }, 8)
    }
    const setHours = () => {
      hours.length = 0
      generateArray(0, 23).forEach(el => hours.push(el))
      setTimeout(() => {
        const index = props.type === 5 || props.type === 7 ? value.value.length - 3 : value.value.length - 2
        value.value[index] = getIndex(hours, hour.value)
      }, 8)
    }
    const setMinutes = () => {
      minutes.length = 0
      generateArray(0, 59).forEach(el => minutes.push(el))
      setTimeout(() => {
        const index = props.type > 4 ? value.value.length - 2 : value.value.length - 1
        value.value[index] = getIndex(minutes, minute.value)
      }, 8)
    }
    const setSeconds = () => {
      seconds.length = 0
      generateArray(0, 59).forEach(el => seconds.push(el))
      setTimeout(() => {
        value.value[value.value.length - 1] = getIndex(seconds, second.value)
      }, 8)
    }
    const pickerChange = (e) => {
      value.value = e.detail.value
      switch (props.type) {
        case 1:
          year.value = years[value.value[0]]
          month.value = months[value.value[1]]
          day.value = days[value.value[2]]
          hour.value = hours[value.value[3]]
          minute.value = minutes[value.value[4]]
          break
        case 2:
          year.value = years[value.value[0]]
          month.value = months[value.value[1]]
          day.value = days[value.value[2]]
          break
        case 3:
          year.value = years[value.value[0]]
          month.value = months[value.value[1]]
          break
        case 4:
          hour.value = hours[value.value[0]]
          minute.value = minutes[value.value[1]]
          break
        case 5:
          hour.value = hours[value.value[0]]
          minute.value = minutes[value.value[1]]
          second.value = seconds[value.value[2]]
          break
        case 6:
          minute.value = minutes[value.value[0]]
          second.value = seconds[value.value[1]]
          break
        case 7:
          year.value = years[value.value[0]]
          month.value = months[value.value[1]]
          day.value = days[value.value[2]]
          hour.value = hours[value.value[3]]
          minute.value = minutes[value.value[4]]
          second.value = seconds[value.value[5]]
          break
        case 8:
          year.value = years[value.value[0]]
          month.value = months[value.value[1]]
          day.value = days[value.value[2]]
          hour.value = hours[value.value[3]]
          break
        default:
          break
      }
    }
    const confirm = () => {
      setTimeout(() => {
        let result = {}
        const _year = year.value
        const _month = formatNum(month.value || 0)
        const _day = formatNum(day.value || 0)
        const _hour = formatNum(hour.value || 0)
        const _minute = formatNum(minute.value || 0)
        const _second = formatNum(second.value || 0)
        switch (props.type) {
          case 1:
            result = {
              year: _year,
              month: _month,
              day: _day,
              hour: _hour,
              minute: _minute,
              result: `${_year}-${_month}-${_day} ${_hour}:${_minute}`
            }
            break
          case 2:
            result = {
              year: _year,
              month: _month,
              day: _day,
              result: `${_year}-${_month}-${_day}`
            }
            break
          case 3:
            result = {
              year: _year,
              month: _month,
              result: `${_year}-${_month}`
            }
            break
          case 4:
            result = {
              hour: _hour,
              minute: _minute,
              result: `${_hour}:${_minute}`
            }
            break
          case 5:
            result = {
              hour: _hour,
              minute: _minute,
              second: _second,
              result: `${_hour}:${_minute}:${_second}`
            }
            break
          case 6:
            result = {
              minute: _minute,
              second: _second,
              result: `${_minute}:${_second}`
            }
            break
          case 7:
            result = {
              year: _year,
              month: _month,
              day: _day,
              hour: _hour,
              minute: _minute,
              second: _second,
              result: `${_year}-${_month}-${_day} ${_hour}:${_minute}:${_second}`
            }
            break
          case 8:
            result = {
              year: _year,
              month: _month,
              day: _day,
              hour: _hour,
              result: `${_year}-${_month}-${_day} ${_hour}:00`
            }
            break
          default:
            break
        }
        emit('confirm', result)
        popupRef.value.close()
      }, 80)
    }

    return {
      popupRef,
      open,
      close,
      cancel,
      confirm,
      value,
      pickerChange,
      reset,
      years,
      months,
      days,
      hours,
      minutes,
      seconds,
      formatNum
    }
  }
}
</script>

<style lang="scss">
.indicator-class {
  height: 88rpx;
  background: #f5f5f5;
  z-index: -1;

  &::after,
  &::before {
    content: none;
  }
}
</style>
<style lang="scss" scoped>
.xui-datepicker__header {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  padding: 0 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  font-size: 32rpx;
  position: relative;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
  background-color: #fff;

  &__cancel {
    color: #bbbbbb;
  }

  &__confirm {
    color: #51a3ff;
  }

  &::after {
    content: "";
    width: 100%;
    height: 1px;
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: #f9f9f9;
  }
}

.xui-datepicker__body {
  height: 520rpx;
  width: 100%;
  overflow: hidden;
  background-color: #fff;

  .xui-datepicker-view {
    height: 100%;
    box-sizing: border-box;

    .xui-datepicker-column-item {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #333;
    }
  }
}
</style>
